package com.le.tester.book.effectivejava3rdchinese.articlenine;

import java.io.*;
import java.util.concurrent.locks.ReentrantLock;

import static org.springframework.util.StreamUtils.BUFFER_SIZE;

/**
 * createTime：2022/8/1 16:50
 * description：使用try-with-resource语句代替try-finally语句
 */
public class TryWithResources {
    static String firstLineOfFile(String path) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(path));
        try {
            return br.readLine();
        } finally {
            br.close();
        }

    }

    static void copy(String src, String dst) throws IOException {
        InputStream in = new FileInputStream(src);
        try {
            OutputStream out = new FileOutputStream(dst);
            try {
                byte[] buf = new byte[BUFFER_SIZE];
                int n;
                while ((n = in.read(buf)) >= 0) {
                    out.write(buf, 0, n);
                }
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    }

    static String firstLineOfFilePlus(String path) throws IOException {

        try (BufferedReader br = new BufferedReader(new FileReader(path))) {
            return br.readLine();
        }
    }

    static void copyPlus(String src, String dst) throws IOException {

        try (InputStream in = new FileInputStream(src);
             OutputStream out = new FileOutputStream(dst)) {

            byte[] buf = new byte[BUFFER_SIZE];
            int n;
            while ((n = in.read(buf)) > 0) {
                out.write(buf, 0, n);
            }
        }
    }

    static void tryLock() {
        ReentrantLock lock = new ReentrantLock();
        boolean tryLockOr = lock.tryLock();
        if (tryLockOr) {
            lock.lock();
            //TODO
        }

    }

    //try-with-resource
    static String firstLineOfFilePlusPlus(String path, String defaultVal) {

        try (BufferedReader br = new BufferedReader(new FileReader(path))) {
            return br.readLine();
        } catch (IOException e) {
            return defaultVal;
        }
    }

}
